﻿using Company.Database.Base.Entities;
using Company.Database.Base.Repositories;

namespace Company.Database.SqlServer.Repositories
{
    class DeviceRepository : IDeviceRepository
    {
        private readonly SqlServerDbContext _context;
        public DeviceRepository(SqlServerDbContext context)
        {
            _context = context;
        }

        public async Task<int> DeleteAsync(DeviceEntity entity)
        {
            return await Task.Run(() =>
            {
                _context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
                return _context.SaveChanges();
            });
        }

        public async Task<List<DeviceEntity>> GetAllAsync()
        {
            return await Task.Run(() =>
            {
                return _context.Devices.ToList();
            });
        }

        public async Task<DeviceEntity> GetByIdAsync(int id)
        {
            return await _context.Devices.FindAsync(id) ?? new DeviceEntity();
        }

        public async Task<int> InsertAsync(DeviceEntity entity)
        {
            await _context.Devices.AddAsync(entity);
            return await _context.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(DeviceEntity entity)
        {
            return await Task.Run(() =>
            {
                _context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
                return _context.SaveChanges();
            });
        }
    }
}
